import { defineFakeRoute } from "vite-plugin-fake-server/client";
import { faker } from "@faker-js/faker/locale/zh_CN";

let hasInit = false;

const data: any[] = [
  {
    id: 1,
    parentId: 0,
    deptName: "XXXX公司"
  },
  {
    id: 3,
    parentId: 1,
    deptName: "成都分公司"
  },
  {
    id: 11,
    parentId: 22,
    deptName: "研发部门"
  },
  {
    id: 12,
    parentId: 22,
    deptName: "市场部门"
  },
  {
    id: 13,
    parentId: 22,
    deptName: "财务部门"
  },
  {
    id: 14,
    parentId: 22,
    deptName: "市场部门"
  },
  {
    id: 15,
    parentId: 3,
    deptName: "财务部门"
  },
  {
    id: 16,
    parentId: 3,
    deptName: "运维部门"
  },
  {
    id: 22,
    parentId: 1,
    deptName: "上海分公司"
  }
];

export const getData = () => {
  if (!hasInit) {
    hasInit = true;
    for (const index in data) {
      data[index] = {
        ...data[index],
        principal: faker.book.author(),
        phone: faker.phone.number(),
        email: faker.internet.email(),
        remark: faker.book.genre(),
        sort: "99",
        status: Math.random() > 0.5 ? true : false,
        createTime: faker.date.between({ from: "2000-01-01", to: Date.now() }),
        updateTime: faker.date.between({ from: "2000-01-01", to: Date.now() })
      };
    }
  }
  return data.sort((a, b) => a.sort - b.sort);
};

export default defineFakeRoute([
  {
    url: "/system/depts",
    method: "get",
    //statusCode: 404,
    response: () => {
      return {
        success: true,
        message: "操作成功",
        data: getData()
      };
    }
  },
  {
    url: "/system/depts",
    method: "post",
    response: ({ body }) => {
      return {
        success: true,
        message: "操作成功",
        data: {
          ...body,
          id: 999
        }
      };
    }
  },
  {
    url: "/system/depts/:id",
    method: "get",
    response: ({ params }) => {
      return {
        success: true,
        message: "操作成功",
        data: getData().find(item => item.id == params.id)
      };
    }
  },
  {
    url: "/system/depts/:id",
    method: "put",
    response: ({ params }) => {
      return {
        success: true,
        message: "操作成功",
        data: getData().find(item => item.id == params.id)
      };
    }
  },
  {
    url: "/system/depts/:id",
    method: "delete",
    statusCode: 404,
    response: () => {
      return {
        success: true,
        message: "操作成功"
      };
    }
  },
  {
    url: "/system/depts",
    method: "delete",
    response: () => {
      return {
        success: false,
        message: "禁止删除"
      };
    }
  }
]);
